﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI;

namespace CH.FourBoards.LagerWalti.FrontEnd.View.Controls
{
	public class ControlBase : UserControl
	{

		public IncludeContainer Includes { get; set; }

		protected T InstallControl<T>(string path) where T : ControlBase
		{
			var ret = (T) LoadControl(path);
			ret.Includes = Includes;
			return ret;
		}

		protected void IncludeCss(string relativePath)
		{
			var path = Root + relativePath;
			Includes.AddStyle(path);
		}

		protected void IncludeScript(string relativePath)
		{
			var path = Root + relativePath;
			Includes.AddScripts(path);
		}

		protected string Root
		{
			get
			{
				var ret = Context.Request.ApplicationPath;
				ret = ret ?? string.Empty;
				if (!ret.EndsWith("/")) {
					ret += "/";
				}
				return ret;
			}
		}

		protected String VirtualFolderPath
		{
			get
			{
				var ret = Path.GetDirectoryName(AppRelativeVirtualPath);
				ret = ret ?? string.Empty;
				ret = ret.Replace("~" + Path.DirectorySeparatorChar, string.Empty);
				ret = ret.Replace(Path.DirectorySeparatorChar, '/');
				if (ret.StartsWith("/")) {
					ret = ret.Substring(1);
				}
				return ret + '/';
			}
		}

		protected string CreateAttributeString(IEnumerable<KeyValuePair<string, string>> attributes)
		{
			var items = attributes.Select(attribute => string.Format("{0}=\"{1}\"", attribute.Key, attribute.Value));
			return string.Join(" ", items);
		}

	}
}